package cn.lzd.mr.case8;

import cn.lzd.mr.PathUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.Random;

/**
 * Created by lzd on 2018/6/6.
 * 数据倾斜场景
 * 数据堆中a的种类众多，负责处理a這个单词的reduce就会很累。
 * 解决方案，给a添加元素，如下。拼上一个随机值处理。
 */
public class Case8MR {

    static class Mp extends Mapper<LongWritable, Text, Text, IntWritable> {
        int num = 0;
        Random random = new Random();
        Text text = new Text();
        IntWritable intWritable = new IntWritable(1);

        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            num = context.getNumReduceTasks();
        }

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String vals = value.toString();
            String[] split = vals.split(" ");
            for (String v : split) {
                text.set(v + "--" + random.nextInt(num));
                context.write(text, intWritable);
            }
        }
    }

    static class Rd extends Reducer<Text, IntWritable, Text, IntWritable> {

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int count = 0;
            for (IntWritable value : values) {
                count += value.get();
            }
            context.write(key, new IntWritable(count));
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        String inpath = PathUtil.getpath("case8") + "*";
        String outpath = PathUtil.getpath("case8") + "out/";

        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration);

        PathUtil.handleOutPath(outpath,configuration);
        job.setNumReduceTasks(3);

        job.setJarByClass(Case8MR.class);
        job.setMapperClass(Mp.class);
        job.setReducerClass(Rd.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.setInputPaths(job, new Path(inpath));
        FileOutputFormat.setOutputPath(job, new Path(outpath));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
